package com.spider.admin.scaffold.common;


import com.spider.admin.scaffold.entity.model.User;
import com.spider.admin.scaffold.exception.BusinessException;
import com.spider.admin.scaffold.exception.ExceptionDef;
import com.spider.admin.scaffold.service.UserService;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * @author xiong.bo
 * @version 1.0
 * @date 2025/3/23 4:49 下午
 */

@Slf4j
@Component
public class UserContext {

  private static final String CURRENT_USER_CACHE_KEY = "currentUserCache";

  @Autowired
  private CacheManager cacheManager;
  @Autowired
  private UserService userService;

  /**
   * 从上下文中的token中获取当前登录用户信息
   */
  public User getUserContent() {

    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if (ObjectUtils.isEmpty(principal)) {
      throw new BusinessException("当前token已过期");
    }
    String username = principal.toString();
    Cache cache = cacheManager.getCache(CURRENT_USER_CACHE_KEY);
    if (cache != null) {
      User user;
      ValueWrapper valueWrapper = cache.get(username);
      if (valueWrapper != null && valueWrapper.get() != null) {
        user = (User) valueWrapper.get();
      } else {
        user = selectUser(username);
        if (user != null) {
          cache.put(username, user);
        }
      }
      return user;
    }
    throw new BusinessException(ExceptionDef.ERROR_USER_TOKEN_INVALID);
  }

  public User selectUser(String username) throws BusinessException {
    User user = userService.findByUsername(username);
    if (Objects.isNull(user)) {
      throw new BusinessException(ExceptionDef.ERROR_USER_TOKEN_INVALID);
    }
    return user;
  }

}
